package com.teragadgets.android.comic;

import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

import com.teragadgets.android.comic.datamodel.Comic;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class ComicListActivity extends Activity implements Observer,
		OnItemClickListener, OnScrollListener {

	private ListView comicList;
	private ComicListModel model;
	private boolean loading = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.main);

		// Initialize Model
		model = new ComicListModel(this, getIntent().getStringExtra(
				"webComicID"));
		model.addObserver(this);

		this.setTitle(model.getWebComic().getName());

		comicList = (ListView) this.findViewById(R.id.comicList);
		Vector<Comic> comics = model.getComics();
		comicList.setAdapter(new ComicAdapter(this, comics, R.layout.comicrow,
				R.id.comicName));
		comicList.setOnItemClickListener(this);

		comicList.setOnScrollListener(this);
	}

	@Override
	public void update(Observable observable, Object data) {
		loading = (Boolean) data;
		((ComicAdapter) comicList.getAdapter()).notifyDataSetChanged();
		comicList.refreshDrawableState();
	}

	private class ComicAdapter extends ArrayAdapter<Comic> {

		public ComicAdapter(Context context, Vector<Comic> comics, int layout,
				int textResource) {
			super(context, layout, textResource, comics);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);

			if (loading && position == this.getCount() - 1) {
				view.findViewById(R.id.itemContent).setVisibility(View.GONE);
				view.findViewById(R.id.itemLoading).setVisibility(View.VISIBLE);
			} else {
				view.findViewById(R.id.itemContent).setVisibility(View.VISIBLE);
				view.findViewById(R.id.itemLoading).setVisibility(View.GONE);
			}
			TextView text = (TextView) view.findViewById(R.id.comicName);
			Comic c = getItem(position);
			if (c.getNumber() == model.getLastRead()
					&& c.getNumber() != model.getWebComic().getNumberOfComics())
				text.setTextColor(Color.RED);
			else
				text.setTextColor(Color.parseColor("#aaaaaa"));
			return view;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Comic selectedComic = (Comic) parent.getAdapter().getItem(position);

		Intent i = new Intent(this, ComicActivity.class);
		i.putExtra("webComicID", getIntent().getStringExtra("webComicID"));
		i.putExtra("comicID", position);
		startActivity(i);
	}

	private int priorTotal = -1;

	@Override
	public void onScroll(AbsListView view, int first, int visible, int total) {

		// detect if last item is visible
		if (total != 0 && first + visible == total) {
			// see if we have more results
			if (total != priorTotal) {
				priorTotal = total;
				onLastListItemDisplayed(total, visible);
			}
		}
	}

	protected void onLastListItemDisplayed(int total, int visible) {
		if (model.getComics().size() < model.getWebComic().getNumberOfComics()) {
			this.update(null, true);
			model.loadComics();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		model.updateWebComic(this);
		((ComicAdapter) comicList.getAdapter()).notifyDataSetChanged();
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}
	
	private final int MENU_ORDER = 0;
	private final int MENU_REFRESH = 1;

	/* Creates the menu items */
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_ORDER, 0, "Change Order").setIcon(
				android.R.drawable.ic_menu_sort_alphabetically);
		menu.add(0, MENU_REFRESH, 0, "Refresh").setIcon(
				android.R.drawable.ic_menu_rotate);
		return true;
	}

	/* Handles item selections */
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_ORDER:
			model.changeOrder(this);
		case MENU_REFRESH:
			model.refresh(this);
		}
		return false;
	}
}
